package com.rockwell.sniffyhunter.model;

import com.rockwell.sniffyhunter.utils.IRobotLogger;
import com.rockwell.sniffyhunter.utils.IStateMachine;
import com.rockwell.sniffyhunter.utils.IStateObject;

public abstract class StateObject implements IStateObject {

	private IRobotLogger m_logger;
	private int m_logLevel = 1;
	
	protected IStateMachine machineRecoveryState;
	protected IStateMachine machineState;
	protected Robot robot;
	
	public StateObject(Robot robot) {
		this.robot = robot;
		setLogger(robot.m_logger, robot.m_logLevel);
		Initialize();
	}
	
	protected abstract void Initialize();
	protected abstract boolean IsDone();
	
	@Override
	public ReturnResult PerformAction() {
		
		machineState = machineState.doAction(this);
		
		if (IsDone()) {
			Initialize();
			return ReturnResult.Completed;
		}
		else {
			return ReturnResult.Continue;
		}
	}

	protected void sleep(int duration) {
		try {
			Thread.sleep(duration);
		} catch (InterruptedException ex) {
			log(ex, 1);
		}
	}

	protected void setLogger(IRobotLogger logger, int level) {
		m_logger = logger;
		m_logLevel = level;
	}
	
	protected void log(String msg, int level) {
		if (m_logger != null && m_logLevel >= level) {
			m_logger.log(msg);
		}
	}
	
	protected void log(Exception ex, int level) {
		if (m_logger != null && m_logLevel >= level) {
			m_logger.log(ex);
		}
	}
	
	@Override
	// For Unit Test Only
	public IStateMachine getStateMachine() {
		return machineState;
	}
}
